package com.example.demo.repository;

import com.example.demo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Repository
public class StudentRepository {

    private static final String STUDENT_KEY_PREFIX = "student:";
    private static final String SORTED_SET_KEY = "students:avgscore";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final String ID_COUNTER_KEY = "student:id:counter";

    @Autowired
    private JedisPool jedisPool;

    public String generateId() {
        try (Jedis jedis = jedisPool.getResource()) {
            return String.valueOf(jedis.incr(ID_COUNTER_KEY));
        }
    }

    public void save(Student student) {
        if (student.getId() == null || student.getId().isEmpty()) {
            student.setId(generateId());
        }
        try (Jedis jedis = jedisPool.getResource()) {
            String key = STUDENT_KEY_PREFIX + student.getId();
            Map<String, String> fields = new HashMap<>();
            fields.put("id", student.getId());
            fields.put("name", student.getName());
            fields.put("birthday", DATE_FORMAT.format(student.getBirthday()));
            fields.put("description", student.getDescription());
            fields.put("avgscore", String.valueOf(student.getAvgscore()));

            jedis.hmset(key, fields);
            jedis.zadd(SORTED_SET_KEY, student.getAvgscore(), student.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Student findById(String id) {
        try (Jedis jedis = jedisPool.getResource()) {
            String key = STUDENT_KEY_PREFIX + id;
            Map<String, String> fields = jedis.hgetAll(key);

            if (fields.isEmpty()) {
                return null;
            }

            Student student = new Student();
            student.setId(fields.get("id"));
            student.setName(fields.get("name"));
            try {
                student.setBirthday(DATE_FORMAT.parse(fields.get("birthday")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            student.setDescription(fields.get("description"));
            student.setAvgscore(Integer.valueOf(fields.get("avgscore")));

            return student;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<Student> findAll(int page, int size) {
        try (Jedis jedis = jedisPool.getResource()) {
            // 修改1：将Set<String>改为List<String>
            List<String> ids = jedis.zrevrange(SORTED_SET_KEY, (page - 1) * size, page * size - 1);
            List<Student> students = new ArrayList<>();

            for (String id : ids) {
                Student student = findById(id);
                if (student != null) {
                    students.add(student);
                }
            }

            return students;
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    public long count() {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.zcard(SORTED_SET_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public void delete(String id) {
        try (Jedis jedis = jedisPool.getResource()) {
            String key = STUDENT_KEY_PREFIX + id;
            jedis.del(key);
            jedis.zrem(SORTED_SET_KEY, id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}    